package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.AddressBookMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.mapper.UserMapper;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.task.WebSocketServer;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Slf4j
@Service
public class OrderServiceImp  implements OrderService {
    @Autowired
    AddressBookMapper addressBookMapper;
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    ShoppingCartMapper shoppingCartMapper;
    @Autowired
    WeChatPayUtil weChatPayUtil;
    @Autowired
    WebSocketServer webSocketServer;
    @Override
    @Transactional
    //todo 调用百度验证方法验证是否超越配送距离
    public OrderSubmitVO summit(OrdersSubmitDTO ordersSubmitDTO) {
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        Long userId = BaseContext.getCurrentId();
        String username = userMapper.getUsernameById(userId);

        List<ShoppingCart> shoppingCarts = shoppingCartMapper.GetByUserId(userId);
        if (shoppingCarts.isEmpty()) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        // 创建插入订单
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setUserId(userId);
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);

        if (username != null && !username.isEmpty()) {
            orders.setUserName(username);
        }

        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee());
        orders.setNumber(String.valueOf(System.currentTimeMillis()));

        orderMapper.insert(orders);

        // 插入订单明细
        List<OrderDetail> orderList = new ArrayList<>();
        for (ShoppingCart shoppingCart : shoppingCarts) {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orders.getId());
            BeanUtils.copyProperties(shoppingCart, orderDetail);
            orderList.add(orderDetail);
        }
        orderMapper.insertDetailBatches(orderList);

        // 清空购物车
        shoppingCartMapper.deleteByUserId(userId);

        // 返回结果
        OrderSubmitVO orderSubmitVO = new OrderSubmitVO();
        orderSubmitVO.setOrderTime(orders.getOrderTime());
        orderSubmitVO.setOrderNumber(orders.getNumber());
        orderSubmitVO.setOrderAmount(orders.getAmount());
        orderSubmitVO.setId(orders.getId());

        return orderSubmitVO;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

//        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );
        JSONObject jsonObject = new JSONObject();
        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);

        //todo 测试一下
        //消息类型，1表示来单提醒
        Map map = new HashMap();
        map.put("type", 1);
        map.put("orderId", orders.getId());
        map.put("content", "订单号：" + outTradeNo);
        webSocketServer.sendToAllClient(JSON.toJSONString(map));

    }

    /**
     * 再来一单就是将原订单中的商品重新加入到购物车中
     * @param id
     */
    @Override
    public void repetition(Long id) {
        List<OrderDetail> orderDetailList = orderMapper.getDetailByOrderId(id);
        Long userId = BaseContext.getCurrentId();
        List<ShoppingCart> scartList = orderDetailList.stream().map(item ->
        {
            ShoppingCart shoppingCart = new ShoppingCart();
            shoppingCart.setUserId(userId);
            BeanUtils.copyProperties(item, shoppingCart, "id");
            shoppingCart.setCreateTime(LocalDateTime.now());

            return shoppingCart;
        }).collect(Collectors.toList());
        shoppingCartMapper.insertBatches(scartList);
    }

    /**
     * 历史订单查询
     * @param
     * @return
     */
    @Override
    public PageResult pageQuery(OrdersPageQueryDTO dto) {
//        开启分页
        PageHelper.startPage(dto.getPage(),dto.getPageSize());
        Long userId = BaseContext.getCurrentId();
        dto.setUserId(userId);
        Page<Orders> ordersList=orderMapper.pageQuery(dto);

        return new PageResult(ordersList.getTotal(),getOrderVOListFromPage(ordersList));

    }

    @Override
    public PageResult searchOrders(OrdersPageQueryDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        Page<Orders> page=orderMapper.pageQuery(dto);
        return new PageResult(page.getTotal(),getOrderVOListFromPage(page));
    }



    public List<OrderVO> getOrderVOListFromPage(Page<Orders> page){
        List<Orders> ordersList = page.getResult();
        ArrayList<OrderVO> orderVOList = new ArrayList<>();
        if (ordersList!=null && ordersList.size()>0)
            ordersList.forEach(item ->
            {
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(item,orderVO);
                List<OrderDetail> orderDetailList = orderMapper.findOrderDetailById(item.getId());
                orderVO.setOrderDetailList(orderDetailList);
                orderVO.setOrderDishes(getOrderDishesStr(item));
                orderVOList.add(orderVO);
            });

        return orderVOList;
    }



    @Override
    public OrderVO detail(Long id) {

        List<OrderDetail> list= orderMapper.findOrderDetailById(id);

        Orders orders=orderMapper.findById(id);
        OrderVO orderVO = new OrderVO();
        orderVO.setOrderDetailList(list);
        BeanUtils.copyProperties(orders,orderVO);
        return orderVO;

    }

    /**
     * 用户取消
     * 业务规则:大于订单状态大于2时不让取消抛异常
     * @param id
     */
    @Override
    public void userCancelById(Long id) {

        Orders orders = orderMapper.getById(id);
        if(orders.getStatus()>2 ||orders ==null){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

//        WeChatPayUtil.REFUNDS(); 模拟退款

        orders.setStatus(Orders.CANCELLED);
        //模拟
        orders.setCancelReason("用户取消了订单");
        orders.setPayStatus(Orders.REFUND);
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);

    }

    /**
     * 订单状态统计
     * @return
     */

    @Override
    public OrderStatisticsVO getOrderStatistics() {

        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();

        Integer toBeConfirmed=orderMapper.findByStatus(Orders.TO_BE_CONFIRMED);
        Integer confirmed = orderMapper.findByStatus(Orders.CONFIRMED);
        Integer deliveryInProgress = orderMapper.findByStatus(Orders.DELIVERY_IN_PROGRESS);

        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        return orderStatisticsVO;
    }

    /**
     * 接单
     * @param id
     */

    @Override
    public void confirmOrder(Long id) {
        Orders orders = Orders.builder()
                .id(id)
                .status(Orders.CONFIRMED)
                .build();

        orderMapper.update(orders);
    }

    /**
     * 商家取消
     * 取消订单其实就是将订单状态修改为“已取消”
     * 商家取消订单时需要指定取消原因
     * 商家取消订单时，如果用户已经完成了支付，需要为用户退款
     * @param ordersCancelDTO
     */

    @Override
    public void aminCancelByDTO(OrdersCancelDTO ordersCancelDTO) {

        Long id = ordersCancelDTO.getId();
        Orders orders = orderMapper.getById(id);

        //模拟退款
//       Long userId = orders.getUserId();
//        if(orders.getPayStatus()==Orders.PAID){
//            String outTradeNo = orders.getNumber();
//            weChatPayUtil.refund(outTradeNo,outTradeNo,orders.getAmount(),orders.getAmount());
//        }

        orders.setCancelTime(LocalDateTime.now());
        String cancelReason = ordersCancelDTO.getCancelReason();
        orders.setCancelReason(cancelReason);
        orders.setPayStatus(Orders.REFUND);
        orders.setStatus(Orders.CANCELLED);
        orderMapper.update(orders);
    }

    @Override
    public void rejectOrder(OrdersRejectionDTO ordersCancelDTO) {
        Orders orders = orderMapper.getById(ordersCancelDTO.getId());

        if(orders.getStatus()!=Orders.TO_BE_CONFIRMED || orders==null)
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);

        //        if(orders.getPayStatus()==Orders.PAID){
//           weChatPayUtil.refund()
//        }
        orders.setRejectionReason(ordersCancelDTO.getRejectionReason());
        orders.setCancelReason(ordersCancelDTO.getRejectionReason());
        orders.setStatus(Orders.CANCELLED);
        orders.setPayStatus(Orders.REFUND);
        orders.setCancelTime(LocalDateTime.now());

        orderMapper.update(orders);

    }

    @Override
    public void completeOrder(Long id) {
        Orders orders = orderMapper.getById(id);
        if(orders.getStatus()==Orders.DELIVERY_IN_PROGRESS)
            orders.setStatus(Orders.COMPLETED);
        else
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        orderMapper.update(orders);
    }

    /**
     * 派送订单
     * @param id
     */
    @Override
    public void deliveryOrder(Long id) {
        Orders orders = orderMapper.getById(id);
        log.info("派送状态:{}",orders.getStatus());
        if(orders.getStatus()==Orders.CONFIRMED )
            orders.setStatus(Orders.DELIVERY_IN_PROGRESS);

        else
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        orderMapper.update(orders);
    }

    /**
     * 获取订单菜品信息
     * @param orders
     * @return
     */
    private String getOrderDishesStr(Orders orders) {
        // 查询订单菜品详情信息（订单中的菜品和数量）
        List<OrderDetail> orderDetailList = orderMapper.getDetailByOrderId(orders.getId());

        // 将每一条订单菜品信息拼接为字符串（格式：宫保鸡丁*3；）
        List<String> orderDishList = orderDetailList.stream().map(x -> {
            String orderDish = x.getName() + "*" + x.getNumber() + ";";
            return orderDish;
        }).collect(Collectors.toList());

        ArrayList<String> arrayList = new ArrayList<>();

        orderDetailList.forEach(item->{
          String orderDish= item.getName()+"*"+item.getNumber()+";";
          arrayList.add(orderDish);
        });

        return String.join("", orderDishList);
    }

    @Override
    public void reminder(Long id) {

        Orders orders = orderMapper.getById(id);
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //2代表用户催单
        Map map = new HashMap();
        map.put("type", 2);
        map.put("orderId", id);
        map.put("content", "订单号：" + orders.getNumber());
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }
}
